package SGNet

import (
	"encoding/binary"
	log "misc/seelog"
	"time"
)

const (
	AGENT_TICKTIME = 1
)

var MessageDispatcher func(*Session, uint16, []byte)

func startAgent(sess *Session) {
	sess.ConnectTime = time.Now()
	sess.LastPacketTime = time.Now()

	for {
		select {
		case msg, ok := <-sess.in:
			if !ok {
				log.Info("连接丢失:", sess.IP.String())
				return
			}
			//Get Handler
			msgId := binary.BigEndian.Uint16(msg[:2])
			if MessageDispatcher != nil {
				MessageDispatcher(sess, msgId, msg[2:])
			}
			sess.PacketTime = time.Now()
			sess.LastPacketTime = sess.PacketTime

		case outdata := <-sess.out:
			_, err := sess.Conn.Write(outdata)
			if err != nil {
				log.Info("Send Error")
			}
		case inmsg := <-sess.InMessageQueue:
			if inmsg.Id == uint16(0) {
				sess.keepAliveTime = inmsg.Param["AliveTime"].(int64)
			}
		default:
			if sess.LastPacketTime.UnixNano()+sess.keepAliveTime < time.Now().UnixNano() {
				log.Info("连接超出keepAliveTime ", sess.IP.String())
				sess.Conn.Close()
				return
			}
		}
	}
}
